namespace Digitalmes.Application.Sys.Menus.Commands;

/// <summary>
/// 更新菜单命令。
/// </summary>
public record UpdateMenuCommand(long Id, SysMenuDto Menu) : IRequest<IResult<bool>>;

internal sealed class UpdateMenuCommandHandler(IRepository<SysMenu> repo) : IRequestHandler<UpdateMenuCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
    {
        var menu = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (menu == null)
        {
            return Result.Failure("未找到要更新的菜单");
        }

        menu.ParentId = request.Menu.ParentId;
        menu.Type = request.Menu.Type;
        menu.Title = request.Menu.Title;
        menu.Name = request.Menu.Name;
        menu.Path = request.Menu.Path;
        menu.Component = request.Menu.Component;
        menu.Icon = request.Menu.Icon;
        menu.IframeSrc = request.Menu.IframeSrc;
        menu.Link = request.Menu.Link;
        menu.KeepAlive = request.Menu.KeepAlive;
        menu.HideInMenu = request.Menu.HideInMenu;
        menu.HideChildrenInMenu = request.Menu.HideChildrenInMenu;
        menu.HideInTab = request.Menu.HideInTab;
        menu.OpenInNewWindow = request.Menu.OpenInNewWindow;
        menu.Authority = request.Menu.Authority;
        menu.Permission = request.Menu.Permission;
        menu.Order = request.Menu.Order;
        menu.Status = request.Menu.Status;

        var ok = await repo.UpdateAsync(menu, m => new 
        {
            m.ParentId,
            m.Type,
            m.Title,
            m.Name,
            m.Path,
            m.Component,
            m.Icon,
            m.IframeSrc,
            m.Link,
            m.KeepAlive,
            m.HideInMenu,
            m.HideChildrenInMenu,
            m.HideInTab,
            m.OpenInNewWindow,
            m.Authority,
            m.Permission,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
